<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="1150px"
    @ok="handleSubmit"
  >
    <Card title="导出配置" :bordered="false" :headStyle="headStyle" style="margin-bottom: 10px">
      <BasicForm @register="registerForm">
        <template #name="{ model, field }">
          <FormItemRest>
            <div class="flex items-center gap-2">
              <Input v-model:value="model[field]" placeholder="请输入" class="flex-1" />
              <Checkbox v-model:checked="dataRef['isSerialNo']">显示序号</Checkbox>
            </div>
          </FormItemRest>
        </template>
        <template #barFontFamily="{ model, field }">
          <FormItemRest>
            <Space>
              <Select
                style="width: 120px"
                v-model:value="model[field]"
                :options="barFontFamily"
                placeholder="请选择"
              />
              <InputNumber
                style="width: 160px"
                v-model:value="dataRef['barFontSize']"
                placeholder="请输入"
                addon-before="大小"
                addon-after="px"
              />
              <InputNumber
                style="width: 160px"
                v-model:value="dataRef['barLineHeight']"
                placeholder="请输入"
                addon-before="行高"
                addon-after="px"
              />
              背景色：<ColorPicker v-model:value="dataRef['barBackColor']" /> 字体颜色：<ColorPicker
                v-model:value="dataRef['barForeColor']"
              />
              <Checkbox v-model:checked="dataRef['barIsBold']">加粗</Checkbox>
            </Space>
          </FormItemRest>
        </template>
        <template #fontFamily="{ model, field }">
          <FormItemRest>
            <Space>
              <Select
                style="width: 120px"
                v-model:value="model[field]"
                :options="barFontFamily"
                placeholder="请选择"
              />
              <InputNumber
                style="width: 160px"
                v-model:value="dataRef['fontSize']"
                placeholder="请输入"
                addon-before="大小"
                addon-after="px"
              />
              <InputNumber
                style="width: 160px"
                v-model:value="dataRef['lineHeight']"
                placeholder="请输入"
                addon-before="行高"
                addon-after="px"
              />
              背景色：<ColorPicker v-model:value="dataRef['backColor']" /> 字体颜色：<ColorPicker
                v-model:value="dataRef['foreColor']"
              />
              <Checkbox v-model:checked="dataRef['isBold']">加粗</Checkbox>
            </Space>
          </FormItemRest>
        </template>

        <template #role>
          <SelectRoleInput
            :roleCodes="dataRef.roleCodes"
            v-model:value="dataRef.roleDescs"
            @change="(val, node) => handleRoleNames(val, node)"
          />
        </template>
      </BasicForm>
    </Card>
    <Card
      title="预览列表（拖动可以调整列宽和位置）"
      :bordered="false"
      :headStyle="headStyle"
      style="margin-bottom: 10px"
    >
      <ViewColumns ref="viewColumnsRef" :isVisualSetCols="false" />
    </Card>
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { Checkbox, Form, Space, Input, InputNumber, Card, Select } from 'ant-design-vue';
  import { formSchema, barFontFamily, setData } from './exportComponent.data';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import {
    getVisualEditExportTemplatePage,
    getVisualCreateExportTemplate,
    getVisualUpdateExportTemplate,
    getVisualAddExportTemplatePage,
  } from '/@/api/module/module';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { ColorPicker } from '/@/components/ColorPicker';
  import { SelectRoleInput } from '/@/components/CustomComp';
  import ViewColumns from '../setupComponent/viewList/viewColumns/index.vue';
  import { headStyle } from '/@/views/pages/managerPage/managerPage.data';

  export default defineComponent({
    name: 'ExportComponentDrawer',
    components: {
      BasicDrawer,
      BasicForm,
      Checkbox,
      FormItemRest: Form.ItemRest,
      Space,
      Input,
      InputNumber,
      ColorPicker,
      SelectRoleInput,
      ViewColumns,
      Card,
      Select,
    },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const { createMessage } = useMessage();
      const viewColumnsRef = ref<any>(null);
      const isUpdate = ref(true);
      let dataRef = ref<any>({});
      const moduleCode = ref('');
      const formCode = ref('');
      const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
        labelWidth: 90,
        schemas: formSchema,
        showActionButtonGroup: false,
      });
      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        resetFields();
        setDrawerProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;
        moduleCode.value = data?.moduleCode;
        formCode.value = data?.formCode;
        dataRef.value = {};
        if (unref(isUpdate)) {
          const res = await getVisualEditExportTemplatePage({ id: data?.record.id });
          dataRef.value = {
            ...res,
            isBold: res.isBold == '1' ? true : false,
            barIsBold: res.barIsBold == '1' ? true : false,
            isSerialNo: res.isSerialNo == '1' ? true : false,
          };
          const columns = res.exportFields || [];
          columns.forEach((item) => {
            item.field = item.fieldName;
            item.name = item.fieldName;
          });
          if (viewColumnsRef.value) {
            if (res.cols) {
              viewColumnsRef.value.dataRef = res.cols;
            }
            viewColumnsRef.value.columns = columns;
          }
        } else {
          const res = await getVisualAddExportTemplatePage({ moduleCode: moduleCode.value });
          const columns = res.exportFields || [];
          columns.forEach((item) => {
            item.field = item.fieldName;
            item.name = item.fieldName;
          });
          if (viewColumnsRef.value) {
            if (res.cols) {
              viewColumnsRef.value.dataRef = res.cols;
            }
            viewColumnsRef.value.columns = columns;
          }
          dataRef.value = {
            barFontFamily: '微软雅黑',
            barFontSize: 12,
            barLineHeight: 30,
            isSerialNo: true,
            barIsBold: true,
            fontFamily: '微软雅黑',
            fontSize: 12,
            lineHeight: 30,
            isBold: true,
            foreColor: '#000',
          };
        }
        setFieldsValue({
          ...dataRef.value,
        });
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

      async function handleSubmit() {
        try {
          const values = await validate();
          const formDate = Object.assign({}, dataRef.value, values);
          setDrawerProps({ confirmLoading: true });
          const cols = viewColumnsRef.value.dataRef;
          const params = {
            ...formDate,
            cols,
            moduleCode: moduleCode.value,
            formCode: formCode.value,
          };
          const data = setData(params, unref(isUpdate));
          if (unref(isUpdate)) {
            await getVisualUpdateExportTemplate(data);
          } else {
            await getVisualCreateExportTemplate(data);
          }
          createMessage.success('操作成功');
          closeDrawer();
          emit('success');
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
      }

      const handleRoleNames = (val, node) => {
        const { dataRef: newDataRef } = node;
        dataRef.value.roleDescs = val;
        dataRef.value.roleCodes = newDataRef['codes'];
      };

      return {
        registerDrawer,
        registerForm,
        getTitle,
        handleSubmit,
        dataRef,
        barFontFamily,
        handleRoleNames,
        moduleCode,
        formCode,
        headStyle,
        viewColumnsRef,
      };
    },
  });
</script>
<style lang="less" scoped>
  :deep(.ant-row) {
    justify-content: center;
  }
</style>
